package myJs.cps

import myJs.Implicits._
import myJs.myPkg.Select2Options
import myJs.myPkg.jquery.{$, JQuery}
import myJs.tool.Tool
import org.scalajs.dom.{Event, html}
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.core.facade.React
import slinky.web.html._

import scala.collection.immutable.SeqMap
import scala.scalajs.js
import scala.scalajs.js.JSConverters._

/**
 * Created by yz on 21/1/2022
 */
@react object PureSelect2MulCp {

  case class Props(name: String = "", optionMap: SeqMap[String, String], hasBv: Boolean = false, formJq: JQuery = $("#form"),
                   value: js.UndefOr[List[String]] = js.undefined,
                   onChange: js.UndefOr[List[String] => Unit] = js.undefined,
                   width: String = "150px", show: Boolean = true)


  val component = FunctionalComponent[Props] { props =>

    val (value, setValue) = useState(List.empty[String])

    val selectRef = React.createRef[html.Select]

    val placeholder = "click to choose"

    def getValue = {
      props.value.map(v => v).getOrElse(value)
    }

    def onChange(vs: List[String]) = {
      props.onChange.toOption match {
        case Some(f) => f(vs)
        case None => setValue(vs)
      }
    }

    useEffect(() => {
      val y = selectRef.current
      val jq = $(y)
      jq.select2Val(getValue.toJSArray)
    }, List(props.value)
    )

    div(style := Style(display = Tool.b2Display(props.show)),
      select(className := "form-control", name := s"${props.name}",
        style := Style(
          width = s"${props.width}"
        ), ref := selectRef
      )
    )

  }

}
